/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.search.filters;

import org.apache.lucene.search.Filter;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.document.Document;

import java.util.BitSet;
import java.util.List;
import java.io.IOException;

import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.common.util.ConvertUtil;

/**
 * <p>This class to filter search results by roles</p>
 * <p/>
 * <p><a href="RolesFilter.java.html"><i>View Source</i></a></p>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.2 $ $Date: 2006/03/16 11:09:39 $
 */
public class RolesFilter extends Filter {

    private String userRoles = null;

    /**
     * Creates new instance of RolesFilter
     *
     * @param userRoles comma-separated list of user roles
     */
    public RolesFilter(String userRoles) {
        if (userRoles == null) {
            this.userRoles = "";
        } else {
            this.userRoles = userRoles.trim();
        }
    }

    /**
     * {@link Filter#bits}.
     */
    public BitSet bits(IndexReader reader) throws IOException
    {
        BitSet bits = new BitSet(reader.maxDoc());

        for (int i = 0; i < reader.maxDoc(); i++) {
            Document document = reader.document(i);
            String docRoles = document.get(SearchManager.ROLES_FIELD);

            if (docRoles == null) {
                docRoles = "";
            } else {
                docRoles = docRoles.trim();
            }

            if (docRoles.length() == 0) {
                bits.set(i);
            } else if (userRoles.length() == 0) {
                continue;
            } else {
                List userRolesList = ConvertUtil.convertStringToList(userRoles, ",", true);
                List docRolesList = ConvertUtil.convertStringToList(docRoles, ",", true);
                for (int j = 0; j < docRolesList.size(); j++) {
                    String docRole = (String) docRolesList.get(j);
                    if (userRolesList.contains(docRole)) {
                        bits.set(i);
                        break;
                    }
                }
            }
        }
        return bits;
    }

}
